<?php

class Cache
{
	static function begin()
	{
		ob_start();
		ob_implicit_flush(0);
	}
	
	static function end()
	{
		$contents = ob_get_contents();
		ob_end_clean();

		return $contents;
	}
	
	static private function checkCanGzip()
	{
		if (headers_sent() || (connection_status()!=0))
			return 0;

		if (strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'x-gzip') !== false)
			return "x-gzip";

		if (strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip') !== false)
			return "gzip";

		return 0;
	}
	
	static function compressStream($stream, $level = 6)
	{
		$ENCODING = Cache::checkCanGzip();
		if ($ENCODING)
		{
			// $stream .= "<p>Tamaño de pagina no comprimida: ".strlen($stream);
			// $stream .= "<br>Tamaño de pagina comprimida: ".strlen(gzcompress($stream, $level));

			$Size = strlen($stream);
			$Crc = crc32($stream);
			$stream = gzcompress($stream, $level);
			$stream = substr($stream, 0, strlen($stream) - 4);
			header("Content-Encoding: ".$ENCODING);
			
			return "\x1f\x8b\x08\x00\x00\x00\x00\x00".$stream.pack('V', $Crc).pack('V', $Size);
		}

		return $stream;
	}
	
	static function endCompressed($level = 6)
	{
		$stream = ob_get_contents();
		ob_end_clean();
		
		return Cache::compressStream($stream, $level);
	}
}
?>